<!-- src/views/back/systemSetting/CreateDictTypeDrawer.vue -->
<template>
  <n-drawer v-model:show="isDrawer" :width="width" :placement="placement">
    <n-drawer-content :title="title" closable>
      <template #footer>
        <n-space>
          <n-button type="primary" :loading="subLoading" @click="formSubmit"> 确认 </n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </template>

      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="110"
      >
        <n-form-item v-if="formParams.parentName" label="上级节点" path="parentName">
          {{ formParams.parentName }}
        </n-form-item>

        <n-form-item label="字典名称" path="dictNm">
          <n-input v-model:value="formParams.dictNm" maxlength="20" placeholder="请输入字典名称" />
        </n-form-item>

        <n-form-item label="字典类型" path="dictType">
          <n-input
            v-model:value="formParams.dictType"
            maxlength="40"
            placeholder="请输入字典类型"
          />
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useMessage } from 'naive-ui';

  // API 导入
  import { addDictType, updateDictType } from '@/api/business/dist';

  // 定义组件属性
  const props = withDefaults(
    defineProps<{
      title?: string;
      width?: number;
    }>(),
    {
      title: '添加根字典',
      width: 450,
    }
  );

  // 定义事件
  const emit = defineEmits<{
    (e: 'reload'): void;
  }>();

  const message = useMessage();
  const formRef = ref();

  // 表单验证规则
  const rules = {
    dictNm: {
      required: true,
      message: '请输入字典名称',
      trigger: ['blur', 'submit'],
    },
    dictType: {
      required: true,
      message: '请输入字典类型',
      trigger: ['blur', 'submit'],
    },
  };

  // 状态数据
  const state = reactive({
    isDrawer: false,
    subLoading: false,
    formParams: {
      dictTypeId: '',
      dictNm: '',
      parentId: '',
      parentName: '',
      dictType: '',
    },
    placement: 'right' as const,
  });

  // 重置表单
  function resetForm() {
    if (formRef.value) {
      formRef.value.restoreValidation();
    }

    state.formParams = {
      dictTypeId: '',
      dictNm: '',
      parentId: '',
      parentName: '',
      dictType: '',
    };
  }

  // 打开根字典抽屉
  function openRootDrawer() {
    resetForm();
    state.isDrawer = true;
  }

  // 打开抽屉
  function openDrawer(data: any, isAddChild: boolean) {
    resetForm();

    if (isAddChild) {
      // 添加子字典
      state.formParams.parentId = data.dictTypeId;
      state.formParams.parentName = data.dictNm;
    } else {
      // 编辑字典
      Object.assign(state.formParams, data);
    }

    state.isDrawer = true;
  }

  // 关闭抽屉
  function closeDrawer() {
    state.isDrawer = false;
  }

  // 表单提交
  async function formSubmit() {
    if (formRef.value) {
      formRef.value.validate(async (errors: boolean) => {
        if (errors) {
          message.error('请填写完整信息');
          return;
        }

        try {
          state.subLoading = true;

          if (state.formParams.dictTypeId) {
            // 更新字典类型
            await updateDictType(state.formParams);
            message.success('更新成功');
          } else {
            // 添加字典类型
            await addDictType(state.formParams);
            message.success('添加成功');
          }

          resetForm();
          closeDrawer();
          emit('reload');
        } catch (error) {
          message.error('操作失败: ' + (error.message || '未知错误'));
        } finally {
          state.subLoading = false;
        }
      });
    }
  }

  // 处理重置
  function handleReset() {
    resetForm();
  }

  // 暴露方法给父组件
  defineExpose({
    openRootDrawer,
    openDrawer,
    closeDrawer,
  });
</script>
